import { useState, useEffect } from 'react'
import { Link as RouterLink } from 'react-router-dom'
import { Menu, X, User as UserIcon } from 'lucide-react'
import { useAuth } from '../context/AuthContext'

const Navbar = () => {
  const [isMenuOpen, setIsMenuOpen] = useState(false)
  const [isScrolled, setIsScrolled] = useState(false)
  const { isAuthenticated, user } = useAuth()

  useEffect(() => {
    const handleScroll = () => {
      setIsScrolled(window.scrollY > 50)
    }
    window.addEventListener('scroll', handleScroll)
    return () => window.removeEventListener('scroll', handleScroll)
  }, [])

  const navItems = [
    { href: '/#home', label: '首页' }
  ]

  const scrollToSection = (e: React.MouseEvent<HTMLAnchorElement, MouseEvent>, href: string) => {
    e.preventDefault()
    // 检查是否在首页
    if (window.location.pathname !== '/') {
      window.location.href = href // 跳转到首页并滚动
    } else {
      const element = document.querySelector(href.substring(2)) // 去掉 '/#'
      if (element) {
        element.scrollIntoView({ behavior: 'smooth' })
      }
    }
    setIsMenuOpen(false)
  }

  return (
    <nav className={`navbar ${isScrolled ? 'scrolled' : ''}`}>
      <div className="navbar-container">
        <RouterLink to="/" className="navbar-logo">
          <div className="logo-icon">🔧</div>
          <span>红小匠·AI</span>
        </RouterLink>
        
        <ul className={`navbar-menu ${isMenuOpen ? 'active' : ''}`}>
          {navItems.map((item) => (
            <li key={item.href}>
              <a href={item.href} onClick={(e) => scrollToSection(e, item.href)}>
                {item.label}
              </a>
            </li>
          ))}
          <li>
            <RouterLink to="/install-guide" onClick={() => setIsMenuOpen(false)} className="install-guide-link">
              安装教程
              <span className="nav-badge">新</span>
            </RouterLink>
          </li>
        </ul>

        <div className="nav-buttons">
          {isAuthenticated ? (
            <RouterLink to="/profile" className="btn-profile">
              <UserIcon size={18} />
              <span>{user?.username}</span>
            </RouterLink>
          ) : (
            <>
              <RouterLink to="/login" className="btn-login">登录</RouterLink>
              <RouterLink to="/register" className="btn-register">注册</RouterLink>
            </>
          )}
        </div>
        
        <button 
          className="navbar-toggle"
          onClick={() => setIsMenuOpen(!isMenuOpen)}
        >
          {isMenuOpen ? <X size={24} /> : <Menu size={24} />}
        </button>
      </div>
    </nav>
  )
}

export default Navbar 